package com.mm.cloth.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.mm.cloth.R;
import com.mm.cloth.rmbg.ClothSegmentationProcessor;
// import com.mm.cloth.utils.BitmapUtils;
// import com.mm.cloth.utils.ImageSaveUtils;
import com.mm.cloth.view.SlideCompareView;

import java.io.IOException;

/**
 * 衣服分割Activity
 * 使用U2Net模型进行衣服分割
 */
public class ClothSegmentationActivity extends AppCompatActivity {
    private static final String TAG = "ClothSegmentationActivity";
    
    // UI组件
    private ImageView btnBack;
    private Button btnSelectImage;
    private Button btnSegmentCloth;
    private Button btnSaveResult;
    private ProgressBar progressBar;
    private SlideCompareView slideCompareView;
    
    // 数据
    private Bitmap originalBitmap;
    private Bitmap currentResultBitmap;
    
    // 处理器
    private ClothSegmentationProcessor clothProcessor;
    
    // 图片选择器
    private ActivityResultLauncher<Intent> imagePickerLauncher;
    
    // 视图模式
    private enum ViewMode {
        ORIGINAL,    // 显示原图
        COMPARE      // 显示对比
    }
    
    private ViewMode currentMode = ViewMode.ORIGINAL;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloth_segmentation);
        
        initViews();
        initImagePicker();
        initClothProcessor();
        setupClickListeners();
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        btnBack = findViewById(R.id.btnBack);
        btnSelectImage = findViewById(R.id.btnSelectImage);
        btnSegmentCloth = findViewById(R.id.btnSegmentCloth);
        btnSaveResult = findViewById(R.id.btnSaveResult);
        progressBar = findViewById(R.id.progressBar);
        slideCompareView = findViewById(R.id.slideCompareView);
        
        // 初始状态
        btnSegmentCloth.setEnabled(false);
        btnSaveResult.setEnabled(false);
        progressBar.setVisibility(View.GONE);
        
        switchToMode(ViewMode.ORIGINAL);
    }
    
    /**
     * 初始化图片选择器
     */
    private void initImagePicker() {
        imagePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    Uri imageUri = result.getData().getData();
                    if (imageUri != null) {
                        loadImageFromUri(imageUri);
                    }
                }
            }
        );
    }
    
    /**
     * 异步初始化衣服分割处理器
     */
    private void initClothProcessor() {
        Log.d(TAG, "开始异步初始化U2Net衣服分割处理器...");

        new Thread(() -> {
            try {
                clothProcessor = new ClothSegmentationProcessor(this);

                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        try {
                            if (isFinishing() || isDestroyed()) {
                                Log.w(TAG, "Activity已销毁，跳过初始化UI更新");
                                return;
                            }
                            
                            if (clothProcessor.isInitialized()) {
                                Log.d(TAG, "U2Net衣服分割处理器初始化成功");
                                Toast.makeText(this, "U2Net衣服分割模型加载成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Log.e(TAG, "U2Net衣服分割处理器初始化失败");
                                Toast.makeText(this, "U2Net模型加载失败", Toast.LENGTH_SHORT).show();
                                clothProcessor = null;
                            }
                        } catch (Exception uiException) {
                            Log.e(TAG, "初始化UI更新异常", uiException);
                        }
                    });
                }

            } catch (Exception e) {
                Log.e(TAG, "U2Net衣服分割处理器初始化异常", e);
                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        try {
                            String errorMsg = "U2Net模型加载失败";
                            if (e.getMessage() != null) {
                                if (e.getMessage().contains("ONNX Runtime不可用")) {
                                    errorMsg = "ONNX Runtime库不可用，请检查依赖";
                                } else if (e.getMessage().contains("模型文件")) {
                                    errorMsg = "模型文件问题，请检查u2net_cloth_seg.onnx";
                                } else {
                                    errorMsg = "模型加载失败：" + e.getMessage();
                                }
                            }
                            Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show();
                            clothProcessor = null;
                        } catch (Exception uiException) {
                            Log.e(TAG, "异常处理UI更新失败", uiException);
                        }
                    });
                }
            }
        }).start();
    }
    
    /**
     * 设置点击监听器
     */
    private void setupClickListeners() {
        btnBack.setOnClickListener(v -> handleBackPress());
        
        btnSelectImage.setOnClickListener(v -> selectImage());
        
        btnSegmentCloth.setOnClickListener(v -> performClothSegmentation());
        
        btnSaveResult.setOnClickListener(v -> saveResult());
    }
    
    /**
     * 选择图片
     */
    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        imagePickerLauncher.launch(intent);
    }
    
    /**
     * 从URI加载图片
     */
    private void loadImageFromUri(Uri uri) {
        try {
            Log.d(TAG, "开始加载图片: " + uri);
            
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            if (bitmap != null) {
                // 压缩图片以避免内存问题
                originalBitmap = compressBitmap(bitmap, 1024, 1024);
                if (originalBitmap != bitmap) {
                    bitmap.recycle();
                }
                
                Log.d(TAG, "图片加载成功，尺寸: " + originalBitmap.getWidth() + "x" + originalBitmap.getHeight());
                
                // 显示原图
                slideCompareView.setOriginalBitmap(originalBitmap);
                switchToMode(ViewMode.ORIGINAL);
                
                // 启用分割按钮
                btnSegmentCloth.setEnabled(true);
                
                Toast.makeText(this, "图片加载成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            Log.e(TAG, "加载图片失败", e);
            Toast.makeText(this, "图片加载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 执行衣服分割
     */
    private void performClothSegmentation() {
        if (originalBitmap == null) {
            Toast.makeText(this, "请先选择图片", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (clothProcessor == null || !clothProcessor.isInitialized()) {
            Toast.makeText(this, "U2Net处理器未初始化，请重启应用", Toast.LENGTH_LONG).show();
            return;
        }
        
        Log.d(TAG, "=== 开始U2Net衣服分割处理 ===");
        
        // 显示进度条
        showProgress();
        
        // 禁用按钮
        btnSegmentCloth.setEnabled(false);
        btnSaveResult.setEnabled(false);
        
        // 异步处理
        new Thread(() -> {
            try {
                Log.d(TAG, "开始U2Net推理处理");
                Log.d(TAG, "原图尺寸: " + originalBitmap.getWidth() + "x" + originalBitmap.getHeight());
                
                // 执行衣服分割
                Bitmap result = clothProcessor.segmentAndApply(originalBitmap);
                
                if (result != null) {
                    Log.d(TAG, "U2Net推理处理完成，结果尺寸: " + result.getWidth() + "x" + result.getHeight());
                    
                    // 检查Activity状态
                    if (isFinishing() || isDestroyed()) {
                        Log.w(TAG, "Activity已销毁，丢弃处理结果");
                        if (!result.isRecycled()) {
                            result.recycle();
                        }
                        return;
                    }
                    
                    // 处理成功
                    final Bitmap finalResult = result;
                    runOnUiThread(() -> {
                        try {
                            if (!isFinishing() && !isDestroyed()) {
                                handleSegmentationSuccess(finalResult);
                            } else {
                                finalResult.recycle();
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "UI更新异常", e);
                            hideProgress();
                        }
                    });
                } else {
                    Log.w(TAG, "U2Net处理失败");
                    if (!isFinishing() && !isDestroyed()) {
                        runOnUiThread(() -> {
                            hideProgress();
                            btnSegmentCloth.setEnabled(true);
                            Toast.makeText(this, "衣服分割失败，请重试", Toast.LENGTH_SHORT).show();
                        });
                    }
                }
                
            } catch (Exception e) {
                Log.e(TAG, "U2Net处理异常", e);
                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        hideProgress();
                        btnSegmentCloth.setEnabled(true);
                        Toast.makeText(this, "衣服分割异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        }).start();
    }

    /**
     * 处理衣服分割成功结果
     * @param resultBitmap 处理结果图像
     */
    private void handleSegmentationSuccess(Bitmap resultBitmap) {
        try {
            if (isFinishing() || isDestroyed()) {
                Log.w(TAG, "Activity已销毁，跳过结果处理");
                if (resultBitmap != null && !resultBitmap.isRecycled()) {
                    resultBitmap.recycle();
                }
                return;
            }

            if (resultBitmap != null) {
                Log.d(TAG, "开始处理衣服分割成功结果");

                // 保存结果
                currentResultBitmap = resultBitmap;

                // 设置对比视图
                slideCompareView.setOriginalBitmap(originalBitmap);
                slideCompareView.setProcessedBitmap(resultBitmap);

                // 切换到对比模式
                switchToMode(ViewMode.COMPARE);

                // 启用按钮
                if (btnSegmentCloth != null) {
                    btnSegmentCloth.setEnabled(true);
                }
                if (btnSaveResult != null) {
                    btnSaveResult.setEnabled(true);
                }

                // 隐藏进度条
                hideProgress();

                // 显示成功消息
                String message;
                if (clothProcessor != null) {
                    message = "U2Net衣服分割完成！滑动查看对比效果\n" +
                             "推理耗时: " + String.format("%.0f", clothProcessor.getInferenceTime()) + "ms";
                } else {
                    message = "衣服分割完成！滑动查看对比效果";
                }

                Toast.makeText(this, message, Toast.LENGTH_LONG).show();

                Log.d(TAG, "=== U2Net衣服分割处理完成 ===");

            } else {
                Log.e(TAG, "结果图像为空");
                hideProgress();
                btnSegmentCloth.setEnabled(true);
                Toast.makeText(this, "衣服分割失败", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            Log.e(TAG, "处理成功结果异常", e);
            hideProgress();
            if (btnSegmentCloth != null) {
                btnSegmentCloth.setEnabled(true);
            }
            Toast.makeText(this, "结果处理异常", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 保存结果
     */
    private void saveResult() {
        if (currentResultBitmap == null) {
            Toast.makeText(this, "没有可保存的结果", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            String fileName = "cloth_segmentation_" + System.currentTimeMillis() + ".png";
            boolean success = saveBitmapToGallery(currentResultBitmap, fileName);

            if (success) {
                Toast.makeText(this, "图片已保存到相册", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "保存图片失败", e);
            Toast.makeText(this, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 切换视图模式
     */
    private void switchToMode(ViewMode mode) {
        currentMode = mode;

        switch (mode) {
            case ORIGINAL:
                slideCompareView.setVisibility(View.VISIBLE);
                slideCompareView.showOriginalOnly();
                break;

            case COMPARE:
                slideCompareView.setVisibility(View.VISIBLE);
                slideCompareView.resetToCenter();
                break;
        }
    }

    /**
     * 显示进度条
     */
    private void showProgress() {
        if (progressBar != null) {
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏进度条
     */
    private void hideProgress() {
        if (progressBar != null) {
            progressBar.setVisibility(View.GONE);
        }
    }

    /**
     * 处理返回按钮
     */
    private void handleBackPress() {
        try {
            // 清理资源
            if (currentResultBitmap != null && !currentResultBitmap.isRecycled()) {
                currentResultBitmap.recycle();
                currentResultBitmap = null;
            }

            if (originalBitmap != null && !originalBitmap.isRecycled()) {
                originalBitmap.recycle();
                originalBitmap = null;
            }

            finish();
        } catch (Exception e) {
            Log.e(TAG, "返回处理异常", e);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.d(TAG, "ClothSegmentationActivity onDestroy");

        // 清理图片资源
        if (originalBitmap != null && !originalBitmap.isRecycled()) {
            originalBitmap.recycle();
            originalBitmap = null;
        }

        if (currentResultBitmap != null && !currentResultBitmap.isRecycled()) {
            currentResultBitmap.recycle();
            currentResultBitmap = null;
        }

        // 释放处理器资源
        if (clothProcessor != null) {
            clothProcessor.release();
            clothProcessor = null;
        }

        // 强制垃圾回收
        System.gc();
    }

    @Override
    public void onBackPressed() {
        handleBackPress();
    }

    /**
     * 压缩Bitmap到指定尺寸
     */
    private Bitmap compressBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
        if (bitmap == null) return null;

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        if (width <= maxWidth && height <= maxHeight) {
            return bitmap;
        }

        float scaleWidth = (float) maxWidth / width;
        float scaleHeight = (float) maxHeight / height;
        float scale = Math.min(scaleWidth, scaleHeight);

        int newWidth = (int) (width * scale);
        int newHeight = (int) (height * scale);

        return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
    }

    /**
     * 保存Bitmap到相册
     */
    private boolean saveBitmapToGallery(Bitmap bitmap, String fileName) {
        try {
            // 简化的保存方法
            String savedPath = MediaStore.Images.Media.insertImage(
                getContentResolver(),
                bitmap,
                fileName,
                "Cloth segmentation result"
            );
            return savedPath != null;
        } catch (Exception e) {
            Log.e(TAG, "保存图片到相册失败", e);
            return false;
        }
    }
}
